package com.taotao.config.service;

import com.alibaba.fastjson.JSONObject;
import com.taotao.config.ConfigMd5;
import com.taotao.config.MayiktCloudClientConfig;
import com.taotao.config.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wangjin
 * @title: ConfigClientService
 * @projectName sw-springcloud
 * @description:
 * @date 2021/11/9 21:58
 */
public class ConfigClientService implements EnvironmentAware {
    private StandardEnvironment environment;
    @Autowired
    private MayiktCloudClientConfig mayiktCloudClientConfig;

    /**
     * 当springmvc IOC容器加载完成后
     * 需要 rest请求 连接到 分布式配置中心
     * server端 获取配置文件内容
     */
    public JSONObject rpcHttpGetConfig() {
        //获取项目中引入jar包的服务名称

        String applicationName = environment.getProperty("spring.application.name");
        Map<String, String> map = new HashMap<>();
        map.put("name", applicationName);
        //发送rest获取配置文件的内容
        JSONObject jsonObject = HttpClientUtils.httpGet("http://127.0.0.1:8099/" + "getConfig", map);
        int code = jsonObject.getInteger("code");
        if (code != 200) {
            return null;
        }
        JSONObject data = jsonObject.getJSONObject("data");

        return data;
    }

    public JSONObject md5Comparison() {
        String applicationName = environment.getProperty("spring.application.name");
        if (StringUtils.isEmpty(applicationName)) {
            return null;
        }
        HashMap<String, String> mapParam = new HashMap<>();
        mapParam.put("name", applicationName);
        mapParam.put("md5", ConfigMd5.getMd5());
        JSONObject result = HttpClientUtils.httpGet(mayiktCloudClientConfig.getServerConfigUrl() + "md5Comparison", mapParam);
        return result;
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = (StandardEnvironment) environment;
    }
}
